package cn.example.handlertest;

import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;

public class MainActivity extends AppCompatActivity implements View.OnClickListener{

    private static final String TAG = "MainActivity";

    private Button btn_star,btn_sendObj;
    private ImageView imageView;

    private Integer [] img_res=new Integer[]{R.mipmap.item1,R.mipmap.item2,R.mipmap.item3,R.mipmap.item4};
    private Handler handler=new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message message) {
            return false;
            //截获消息
        }
    }){

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            //接受消息的地方
            Log.d(TAG, "handleMessage: "+msg);
        }
    };

    //传递对象数据
    class Person{
        private String name;
        private String age;

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        public String getAge() {
            return age;
        }

        public void setAge(String age) {
            this.age = age;
        }

        public Person(String name, String age) {
            this.name = name;
            this.age = age;
        }
        @Override
        public String toString() {
            return "Person{" +
                    "name='" + name + '\'' +
                    ", age='" + age + '\'' +
                    '}';
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        btn_star=findViewById(R.id.btn_star);
        btn_sendObj=findViewById(R.id.btn_sendObj);
        imageView=findViewById(R.id.imageView);
        btn_star.setOnClickListener(this);
        btn_sendObj.setOnClickListener(this);
    }

    private changeImg changeI=new changeImg();
    class changeImg implements Runnable{
        private int i;
        @Override
        public void run() {
            i++;
            int j = this.i % 3;
            imageView.setBackgroundResource(img_res[j]);
            //延迟一秒交换图片
            handler.postDelayed(changeI,1000);
        }
    }
    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.btn_star:
                handler.postDelayed(changeI,1000);
                break;
            case R.id.btn_sendObj:
                Message message = new Message();
                //Message message1 = handler.obtainMessage();
                message.obj=new Person("dgw","21");
                handler.sendMessage(message);
                message.sendToTarget();
                break;
        }
    }
}
